import React, { useState, useEffect } from 'react';
import { Box, Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField, Alert, DialogContentText } from '@mui/material';
import { TimePicker } from '@mui/x-date-pickers';
import { format, isAfter, isBefore, isSameSecond } from 'date-fns';
import { Meeting } from '../types';

export interface MeetingFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (meeting: Meeting) => void;
  onDelete?: () => void;
  meeting?: Meeting | null;
  selectedDate: Date | null;
}

export const MeetingForm: React.FC<MeetingFormProps> = ({
  isOpen,
  onClose,
  onSave,
  onDelete,
  meeting,
  selectedDate
}) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [startTime, setStartTime] = useState<Date | null>(null);
  const [endTime, setEndTime] = useState<Date | null>(null);
  const [error, setError] = useState('');
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  useEffect(() => {
    if (meeting) {
      setTitle(meeting.title);
      setDescription(meeting.description || '');
      setStartTime(new Date(meeting.start));
      setEndTime(new Date(meeting.end));
    } else {
      setTitle('');
      setDescription('');
      const now = new Date();
      const nextHour = new Date(now);
      nextHour.setHours(now.getHours() + 1, 0, 0, 0);
      setStartTime(nextHour);
      setEndTime(new Date(nextHour.getTime() + 60 * 60 * 1000));
    }
    setError('');
  }, [meeting]);

  const handleSave = () => {
    if (!startTime || !endTime || !selectedDate) {
      setError('请选择开始和结束时间');
      return;
    }

    if (!title.trim()) {
      setError('请输入会议标题');
      return;
    }

    const start = new Date(selectedDate);
    start.setHours(startTime.getHours(), startTime.getMinutes(), 0, 0);

    const end = new Date(selectedDate);
    end.setHours(endTime.getHours(), endTime.getMinutes(), 0, 0);

    const now = new Date();
    if (isBefore(start, now)) {
      setError('不能创建过去时间的会议');
      return;
    }

    if (isSameSecond(start, end) || isAfter(start, end)) {
      setError('结束时间必须晚于开始时间');
      return;
    }

    onSave({
      id: meeting?.id || Math.random().toString(36).substr(2, 9),
      title: title.trim(),
      start: start.toISOString(),
      end: end.toISOString(),
      description: description.trim() || undefined,
    });
  };

  return (
    <>
      <Dialog
        open={isOpen}
        onClose={onClose}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {meeting ? '编辑会议' : '创建新会议'}
          {selectedDate && (
            <Box>
              日期：{format(selectedDate, 'yyyy年MM月dd日')}
            </Box>
          )}
        </DialogTitle>
        <DialogContent sx={{
          pt: 2,
          '& .MuiTextField-root': { mb: 2 },
          '& .MuiFormControl-root': { width: '100%' }
        }}>
          <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}
            <TextField
              label="会议标题"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
            />
            <TextField
              label="会议描述"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              multiline
              rows={3}
            />
            <TimePicker
              label="开始时间"
              value={startTime}
              onChange={(newValue) => setStartTime(newValue)}
              ampm={false}
              format="HH:mm"
            />
            <TimePicker
              label="结束时间"
              value={endTime}
              onChange={(newValue) => setEndTime(newValue)}
              ampm={false}
              format="HH:mm"
            />
          </Box>
          <DialogActions sx={{ margin: 0, padding: 0 }}>
            <Box sx={{ display: 'flex', justifyContent: meeting ? 'space-between' : 'flex-end', width: '100%' }}>
              {meeting && onDelete && (
                <Button
                  onClick={() => setIsDeleteDialogOpen(true)}
                  color="error"
                  variant="outlined"
                >
                  删除会议
                </Button>
              )}
              <Box>
                <Button onClick={onClose}>
                  取消
                </Button>
                <Button onClick={handleSave} variant="contained" color="primary" sx={{ ml: 1 }}>
                  保存
                </Button>
              </Box>
            </Box>
          </DialogActions>
        </DialogContent>

      </Dialog>

      <Dialog
        open={isDeleteDialogOpen}
        onClose={() => setIsDeleteDialogOpen(false)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除这个会议吗？此操作无法撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setIsDeleteDialogOpen(false)}>取消</Button>
          <Button
            onClick={() => {
              onDelete?.();
              setIsDeleteDialogOpen(false);
            }}
            color="error"
            variant="contained"
          >
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};
